package com.orderVideo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orderVideo.common.Result;
import com.orderVideo.dto.VideoCoverDTO;
import com.orderVideo.dto.VideoPageDTO;
import com.orderVideo.entity.Video;
import com.orderVideo.exception.BusinessException;
import com.orderVideo.mapper.VideoMapper;
import com.orderVideo.service.VideoService;
import com.orderVideo.utils.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/video")
//@RequestMapping("/api2/video")
public class VideoController {

	@Autowired
	private VideoService videoService;

	@Autowired
	private VideoMapper videoMapper;

	@Value("${video.cover.path}")
	private String videoCoverPath;

	@Value("${video.upload.path}")
	private String videoUploadPath;

	@PostMapping("/upload")
	public Result<Video> uploadVideo(@RequestParam("file") MultipartFile file,
									 @RequestParam("description") String description) {
		try {
			log.info("开始上传视频---:{}", DateUtil.formatDateTime(new Date()));
			// 从LoginUser获取当前用户ID
			Long userId = LoginUser.getUserId();
			if (userId == null) {
				return Result.error("用户未登录");
			}

			Video video = videoService.uploadVideo(file, description);
			log.info("结束上传视频---:{}", DateUtil.formatDateTime(new Date()));
			return Result.success(video);
		} catch (Exception e) {
			log.error("视频上传失败", e);
			return Result.error(e.getMessage());
		}
	}

	@GetMapping("/{id}")
	public Result<Video> getVideo(@PathVariable Long id) {
		try {
			Video video = videoService.getVideoById(id);
			return Result.success(video);
		} catch (Exception e) {
			return Result.error(e.getMessage());
		}
	}

	/**
	 * 获取用户视频封面
	 */
	@GetMapping("/covers")
	public Result<List<VideoCoverDTO>> getUserVideoCovers() {
		try {
			// 1. 查询用户的所有视频
			List<Video> videos = videoService.lambdaQuery()
					.eq(Video::getUserId, LoginUser.getUserId())
					.list();

			if (videos.isEmpty()) {
				return Result.success(Collections.emptyList());
			}
			// 2. 构建返回数据
			List<VideoCoverDTO> coverList = new ArrayList<>();
			for (Video video : videos) {
				VideoCoverDTO dto = new VideoCoverDTO();
				dto.setVideoId(video.getVideoId());
				dto.setVideoName(video.getVideoName());
				if (video.getVideoImgPath() != null) {
					// 3. 读取封面图片并转换为Base64
					String coverPath = videoCoverPath + video.getVideoImgPath();
					File coverFile = new File(coverPath);
					if (coverFile.exists()) {
						byte[] imageBytes = FileUtil.readBytes(coverFile);
						String base64Image = Base64.getEncoder().encodeToString(imageBytes);
						dto.setCoverBase64("data:image/jpeg;base64," + base64Image);
					}
					dto.setDescription(video.getDescription());
					dto.setOrderPlays(video.getOrderPlays());
					dto.setVideoPath(video.getVideoPath());
					dto.setVideoPushTime(video.getVideoPushTime());
					coverList.add(dto);
				}
			}
			return Result.success(coverList.stream()
					.sorted(Comparator.comparing(VideoCoverDTO::getVideoPushTime, Comparator.reverseOrder()))
					.toList());
		} catch (Exception e) {
			log.error("获取视频封面失败", e);
			return Result.error("获取视频封面失败");
		}
	}

	/**
	 * 视频流播放接口
	 *
	 * @param videoPath 视频文件路径
	 * @return 视频流数据
	 */
	@GetMapping("/videoStream")
	public ResponseEntity<Resource> streamVideo(@RequestParam("videoPath") String videoPath) {
		log.info("开始处理视频流请求，视频路径参数: {}", videoPath);
		try {
			// 构建完整的视频文件路径
			String fullPath = videoUploadPath + videoPath;
			log.info("完整的视频文件路径: {}", fullPath);

			File videoFile = new File(fullPath);
			if (!videoFile.exists()) {
				log.error("视频文件不存在: {}", fullPath);
				throw new BusinessException("视频文件不存在");
			}
			log.info("成功找到视频文件，大小: {} bytes", videoFile.length());

			// 创建文件系统资源
			Resource resource = new FileSystemResource(videoFile);
			String contentType = Files.probeContentType(videoFile.toPath());
			log.info("视频文件类型: {}", contentType);

			// 返回视频流
			return ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_TYPE, contentType)
					.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(videoFile.length()))
					.body(resource);
		} catch (Exception e) {
			log.error("视频流播放失败", e);
			return ResponseEntity.internalServerError().build();
		}
	}

	@PutMapping("/admin/update")
	public Result<Void> updateVideo(@RequestBody Video video) {
		try {
			// 更新视频信息
			videoMapper.updateById(video);
			return Result.success();
		} catch (Exception e) {
			log.error("更新视频信息失败", e);
			return Result.error("更新视频信息失败");
		}
	}

	@DeleteMapping("/admin/{videoId}")
	public Result<String> deleteVideo(@PathVariable("videoId") Long videoId) {
		try {
			// 获取视频信息
			Video video = videoService.getVideoById(videoId);
			if (video == null) {
				return Result.error("视频不存在");
			}

			// 删除视频文件
			String videoFilePath = videoUploadPath + video.getVideoPath();
			File videoFile = new File(videoFilePath);
			if (videoFile.exists()) {
				videoFile.delete();
			}

			// 删除封面文件
			String coverFilePath = videoCoverPath + video.getVideoImgPath();
			File coverFile = new File(coverFilePath);
			if (coverFile.exists()) {
				coverFile.delete();
			}

			// 删除数据库记录
			videoMapper.deleteById(videoId);

			return Result.success("视频删除成功");
		} catch (Exception e) {
			log.error("删除视频失败", e);
			return Result.error("删除视频失败");
		}
	}

	/**
	 * 分页获取视频列表
	 *
	 * @param pageDTO 分页查询参数
	 * @return 视频分页列表
	 */
	@PostMapping("/admin/list")
	public Result<IPage<Video>> getVideoList(@RequestBody VideoPageDTO pageDTO) {
		try {
			IPage<Video> page = new Page<>(pageDTO.getPage(), pageDTO.getSize());
			IPage<Video> videoPage = videoService.getVideoList(page, pageDTO.getUserId());
			return Result.success(videoPage);
		} catch (Exception e) {
			log.error("获取视频列表失败", e);
			return Result.error("获取视频列表失败: " + e.getMessage());
		}
	}

	@PostMapping("/updateCover")
	public Result<String> updateCover(@RequestParam("videoId") Long videoId,
									  @RequestParam("file") MultipartFile file) {
		try {
			// 1. 查询视频是否存在
			Video video = videoService.getVideoById(videoId);
			if (video == null) {
				return Result.error("视频不存在");
			}
			// 2. 根据路径+名称判断视频文件是否存在
			String dbVideoFilePath = videoUploadPath + video.getVideoPath();
			// 如果存在视频文件
			String extension = FileUtil.extName(file.getOriginalFilename());
			String coverFileName = videoId + "." + extension;
			String coverFilePath = videoCoverPath + coverFileName;
			if (FileUtil.exist(dbVideoFilePath)) {
				FileUtil.del(videoCoverPath + video.getVideoImgPath());
				try (InputStream inputStream = file.getInputStream()) {
					FileUtil.writeFromStream(inputStream, coverFilePath);
				}
			}
			// 4. 更新视频的封面路径
			video.setVideoImgPath(coverFileName);
			videoMapper.updateById(video);
			return Result.success("封面更新成功");
		} catch (Exception e) {
			log.error("更新封面失败", e);
			return Result.error("更新封面失败: " + e.getMessage());
		}
	}


} 